package com.yyk.yiliao.ui.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;

import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.Login_Info;
import com.yyk.yiliao.bean.Sendsms_Info;
import com.yyk.yiliao.bean.Wxauthorization_Info;
import com.yyk.yiliao.cache.UserCacheManager;
import com.yyk.yiliao.ui.Main_Activity;
import com.yyk.yiliao.ui.gongyong.activity.WebViewActivity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.OkHttp3Utlis;
import com.yyk.yiliao.util.rx.ApiService;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LogIn_Activity extends BaseActivity {

    @BindView(R.id.mLogin_edit)
    TextView mLoginEdit;
    @BindView(R.id.mLogin_log)
    Button mLoginLog;
    @BindView(R.id.mLogin_telphone)
    EditText mLoginTelphone;
    @BindView(R.id.mLogin_cade)
    EditText mLoginCade;
    @BindView(R.id.mLogin_exit)
    RelativeLayout mLoginExit;
    @BindView(R.id.mLogin_xieyi)
    LinearLayout mLoginXieyi;
    @BindView(R.id.mLogin_weixin)
    LinearLayout mLoginWeixin;
    UMShareAPI umShareAPI;


    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        initToolbar();
//      UMShareAPI.get(this);
        initHawk();
    }

    private void initToolbar() {
        hidetoolBar();
    }

    @Override
    public void initData() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    }

    private void initHawk() {
        //为了让用户每次打开app显示登陆一次 ,暂时去掉了
//        Hawk.put("MAIN_ACTIVITY", "1");
    }


    @OnClick({R.id.mLogin_edit, R.id.mLogin_log, R.id.mLogin_exit, R.id.mLogin_xieyi, R.id.mLogin_weixin})
    public void onViewClicked(View view) {
        final String telphone = mLoginTelphone.getText().toString().trim();
        String cade = mLoginCade.getText().toString().trim();

        switch (view.getId()) {
            case R.id.mLogin_edit:
                String trim = mLoginTelphone.getText().toString().trim();
                if (trim.length() != 11) {
                    ToastUtil.showShort(LogIn_Activity.this, "请正确输入手机号");
                    return;
                } else if (trim.length() == 11) {
                    Map<String, String> map = new TreeMap<>();
                    map.put("telphone", telphone);
                    map.put("sign", Md5Util2.createSign(map));

                    OkHttp3Utlis.getIntance().postOkhttp(ApiService.BASE_URL + "/mobile/Alidayu/sendSMS", map, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string().trim();
                            if (result.length() < 0) {
                                ToastUtil.showShort(mActivity, "短信获取次数过多");
                                return;
                            } else {
                                Logger.i("短信" + result);
                                if (result != null) {
                                    Gson gson = new Gson();
                                    Sendsms_Info sendsms_info = gson.fromJson(result, Sendsms_Info.class);
                                    if (sendsms_info.getCode() == 0) {

                                    } else {
                                        if (sendsms_info.getCode() == 1) {
                                            int cadeSms = sendsms_info.getData();//获取到的验证码
                                            Logger.i("手机验证码" + cadeSms + "");
                                            //存着输入验证码的手机号
                                            Hawk.put("telphone", telphone);
                                            Hawk.put("caseSms", cadeSms);
                                        }
                                    }

                                }
                            }
                        }
                    });
                    TimeCount timeCount = new TimeCount(60000, 1000);
                    timeCount.start();
                }
                break;
            case R.id.mLogin_log:
                if (TextUtils.isEmpty(telphone)) {
                    Toast.makeText(LogIn_Activity.this, "手机号  空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(cade)) {
                    Toast.makeText(LogIn_Activity.this, "验证码  空", Toast.LENGTH_SHORT).show();
                    return;
                }
                Logger.i("code=" + cade + "||" + "code=" + Hawk.get("caseSms"));
                Logger.i("telphone=" + telphone + "||" + "telphoneSms=" + Hawk.get("telphone"));
//                if (cade == Hawk.get("caseSms") & telphone == Hawk.get("telphone")) {


//                Map<String, String> map2 = new TreeMap<>();
//                map2.put("telphone",  "13370145535");
////                map2.put("code", Hawk.get("caseSms") + "");
//                map2.put("code" ,"9160");
//                map2.put("sign", Md5Util2.createSign(map2));
                Map<String, String> map2 = new TreeMap<>();
                map2.put("telphone", telphone + "");
                map2.put("code", cade + "");
                map2.put("sign", Md5Util2.createSign(map2));


                OkHttp3Utlis.getIntance().postOkhttp(ApiService.BASE_URL + "/mobile/common/login", map2, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        Logger.i("登陆账号" + result);
                        Gson gson = new Gson();
                        final Login_Info login_info = gson.fromJson(result, Login_Info.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (login_info.getCode() == 1) {
                                    // todo zk  登录成功，将用户的环信ID、昵称和头像缓存在本地
                                    String userId = login_info.getData().getChat_id();
                                    String nickName = login_info.getData().getReal_name();
                                    String avatarUrl = login_info.getData().getPic();
                                    UserCacheManager.save(userId, nickName + "", avatarUrl);
                                    Logger.e("登录前的" + userId + "_" + avatarUrl + "_" + nickName);

                                    //登录
                                    EMClient.getInstance().login(login_info.getData().getChat_id() + "", "ca9b09d8d1f9", new EMCallBack() {//回调
                                        @Override
                                        public void onSuccess() {
                                            runOnUiThread(new Runnable() {
                                                public void run() {
                                                    // ** manually load all local groups and conversation
                                                    EMClient.getInstance().groupManager().loadAllGroups();
                                                    EMClient.getInstance().chatManager().loadAllConversations();
                                                    //    Log.d("main", "登录聊天服务器成功！");
                                                    ToastUtil.showShort(mActivity, "登录成功");

                                                }
                                            });
                                        }

                                        @Override
                                        public void onProgress(int progress, String status) {

                                        }

                                        @Override
                                        public void onError(int code, String message) {
                                            if (code == -1005) {
                                                message = "用户名或密码错误";
                                            }
                                            final String msg = message;
                                            runOnUiThread(new Runnable() {
                                                public void run() {
                                                    Log.d("main", "登陆聊天服务器失败！");

                                                }
                                            });
                                        }
                                    });
                                    Login_Info.DataBean data = login_info.getData();
                                    Hawk.put("uid", data.getUid());//用户Id
                                    Hawk.put("real", data.getReal());//身份认证
                                    Hawk.put("statusfo", data.getStatusfo()); //鲁亿通
                                    Hawk.put("real_name", data.getReal_name());//姓名
                                    Hawk.put("phone", data.getPatient_phone());//手机号
                                    if (!TextUtils.isEmpty(data.getPic())) {
                                        Hawk.put("wxpic", data.getPic());//微信登陆的时候有照片
                                    }
                                    LogIn_Activity.this.finish();
                                } else {
                                    ToastUtil.showShort(null, login_info.getMsg() + "");
                                }
                            }
                        });


                    }
                });
//        } else{
//            Toast.makeText(LogIn_Activity.this, "验证码   错误", Toast.LENGTH_SHORT).show();
//
//        }
                break;
            case R.id.mLogin_exit:
                Intent intent = new Intent(LogIn_Activity.this, Main_Activity.class);
                startActivity(intent);
                this.finish();
                break;

            case R.id.mLogin_xieyi:
                Intent intent2 = new Intent(LogIn_Activity.this, WebViewActivity.class);
                intent2.putExtra("toolbar_tv", "云医康用户协议");
                intent2.putExtra("url", "http://www.chunmaihealth.com/yyk/views/Shared/Agreement.html?from=app&Sources=3");
                startActivity(intent2);
                break;
            case R.id.mLogin_weixin:
                boolean install = UMShareAPI.get(this).isInstall(this, SHARE_MEDIA.WEIXIN);
                //true 代表安装了客户端
                if (install) {
                    Toast.makeText(LogIn_Activity.this, "客户端安装 授权", Toast.LENGTH_LONG).show();
                    UMShareConfig config = new UMShareConfig();
                    config.isNeedAuthOnGetUserInfo(true);
                    UMShareAPI.get(LogIn_Activity.this).setShareConfig(config);
                    authorization(SHARE_MEDIA.WEIXIN);
                } else {
                    Toast.makeText(LogIn_Activity.this, "微信客户端没有安装", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    UMAuthListener authListener = new UMAuthListener() {
        private String openid;
        private String image_url;
        private String unionid;

        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Logger.i("onStart " + "授权开始");
            //每次启动点开微信授权 ，暂时不能用
//                UMShareConfig config = new UMShareConfig();
//                config.isNeedAuthOnGetUserInfo(false);
//                UMShareAPI.get(LogIn_Activity.this).setShareConfig(config);
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Logger.i("onComplete " + "授权完成");
            Set<String> set = data.keySet();
            for (String string : set) {
                // 设置头像
                if (string.equals("iconurl")) {
                    image_url = data.get(string);
                    Logger.i("微信成功头像" + image_url);
                }
                // 设置ID
                if (string.equals("openid")) {
                    openid = data.get(string);
                    Logger.i("微信成功openid:" + openid);
                }
                //设置微信端唯一标志
                if (string.equals("unionid")) {
                    unionid = data.get(string);
                    Logger.i("微信成功unionid:" + unionid);
                }
            }
            Map<String, String> map = new TreeMap<>();
            map.put("pic", image_url);
            map.put("openid", openid);
            map.put("unionid", unionid);
            map.put("sign", Md5Util2.createSign(map));
            //微信UID
            OkHttp3Utlis.getIntance().getOkHttp(ApiService.BASE_URL + "/mobile/Common/wxauthorization", map, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string().trim();
                    Logger.i("微信授权检测" + result);
                    Gson gson = new Gson();
                    Wxauthorization_Info info = gson.fromJson(result, Wxauthorization_Info.class);
                    if (info.getCode() == 1) {
                        Wxauthorization_Info.DataBean data = info.getData();
                        Hawk.put("uid", data.getUid());//用户Id
                        Hawk.put("real", data.getReal());//身份认证
                        Hawk.put("statusfo", data.getBank_type()); //鲁亿通
                        Hawk.put("real_name", data.getReal_name());//姓名
                        Hawk.put("phone", data.getPatient_phone());//手机号
                        if (!TextUtils.isEmpty(data.getPic())) {
                            Hawk.put("wxpic", data.getPic());//微信登陆的时候有照片
                        }
                        // todo zk  登录成功，将用户的环信ID、昵称和头像缓存在本地
                        String userId = info.getData().getChat_id();
                        String nickName = info.getData().getReal_name();
                        String avatarUrl = info.getData().getPic();
                        UserCacheManager.save(userId, nickName + "", avatarUrl);
                        Logger.e("登录前的" + userId + "_" + avatarUrl + "_" + nickName);

                        //登录
                        EMClient.getInstance().login(info.getData().getChat_id() + "", "ca9b09d8d1f9", new EMCallBack() {//回调
                            @Override
                            public void onSuccess() {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        // ** manually load all local groups and conversation
                                        EMClient.getInstance().groupManager().loadAllGroups();
                                        EMClient.getInstance().chatManager().loadAllConversations();
                                        //    Log.d("main", "登录聊天服务器成功！");
                                        ToastUtil.showShort(mActivity, "登录成功");

                                    }
                                });
                            }

                            @Override
                            public void onProgress(int progress, String status) {

                            }

                            @Override
                            public void onError(int code, String message) {
                                if (code == -1005) {
                                    message = "用户名或密码错误";
                                }
                                final String msg = message;
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        Log.d("main", "登陆聊天服务器失败！");
//                                            ToastUtil.showShort(mActivity, "登陆聊天服务器失败");

                                    }
                                });
                            }
                        });
                        finish();
                    } else if (info.getCode() == 1004) {
                        EventBus.getDefault().postSticky(info);
                        Bundle bundle = new Bundle();
                        bundle.putString("oppenid", info.getData().getOpenid());
                        bundle.putString("pic", info.getData().getPic());
                        bundle.putString("uid", info.getData().getUid() + "");
                        bundle.putString("unionid", unionid + "");
                        startAct(WxLogIn_Activity.class, true, bundle);
                    }
                }
            });
//                Toast.makeText(getApplicationContext(), "image_url=" + image_url + ",unionid=" + unionid, Toast.LENGTH_SHORT).show();
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Logger.i("onError " + "授权失败");

        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Logger.i("onCancel " + "授权取消");

        }
    };

    /**
     * 微信授权 一次 可以用这个解决
     *
     * @param share_media
     */
    private void authorization(SHARE_MEDIA share_media) {
        UMShareAPI.get(this).getPlatformInfo(this, share_media, authListener);
    }

    @Override//结果   必须添加的
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 设置 60秒时间 倒计时
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            mLoginEdit.setBackgroundColor(Color.parseColor("#B6B6D8"));
            mLoginEdit.setClickable(false);
            mLoginEdit.setText("(" + millisUntilFinished / 1000 + ") 秒重新发送");
        }

        @Override
        public void onFinish() {
            mLoginEdit.setText("重新获取验证码");
            mLoginEdit.setClickable(true);
//            mLoginEdit.setBackgroundColor(Color.parseColor("#4EB84A"));

        }

    }


    /**
     * 在使用分享或者授权的Activity中，重写onDestory()方法
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }


}
